package cn.icare.cms.sync;

import cn.icare.cms.*;
import cn.icare.cms.dao.mapper.OrderAddressMapper;
import cn.icare.cms.dao.mapper.OrderItemMapper;
import cn.icare.cms.dao.po.*;
import cn.icare.cms.impl.ItemCatServiceImpl;
import cn.icare.cms.model.feige.ro.FeigeMessageInfo;
import cn.icare.cms.model.ro.AddOrderRo;
import cn.icare.cms.model.ro.OrderAddressRo;
import cn.icare.cms.model.ro.OrderItemRo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.netty.handler.codec.http.HttpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;

/**
 * @Classname SyncOrderService
 * @Description TODO
 * @Date 2020/3/19 19:06
 * @Created by Administrator
 */
@Service
public class SyncOrderService {

    @Autowired
    private OrderService service;

    @Autowired
    private MemberCouponService memberCouponService;

    @Resource
    private OrderAddressMapper orderAddressMapper;

    @Resource
    private OrderItemMapper orderItemMapper;

    @Autowired
    private OrderPayingService orderPayingService;

    @Autowired AreaService areaService;

    private final Logger logger = LoggerFactory.getLogger(SyncOrderService.class);

    /**
     * 创建新订单
     *
     * @param orderRo
     * @param couponId 优惠券Id
     * @return 返回订单Id
     */
    public Long createNewOrder(AddOrderRo orderRo, Integer couponId) {
        long result = 0L;
        try {
            //实付金额,先用商品原价总金额设置
            BigDecimal ammount = orderRo.getSumamount();
            orderRo.setDisamount(new BigDecimal(0));//优惠金额

            //实付金额计算-减去优惠券金额
            if (couponId != null && couponId > 0) {
                //获取优惠券
                Map map = memberCouponService.getMemberCouponOne(orderRo.getMemberid(), couponId);
                if (map != null) {
                    BigDecimal couponNum = new BigDecimal(map.get("num").toString());
                    BigDecimal needNum = new BigDecimal(map.get("neednum").toString());
                    if (orderRo.getSumamount().compareTo(needNum) >= 0) {
                        orderRo.setDisamount(couponNum);//优惠额
                        ammount = ammount.subtract(couponNum); //
                        // orderRo.setAmmount(orderRo.getAmmount().subtract(couponNum));//实付金额
                    }
                }
            }
            //实付金额计算-加上配送费
            if (orderRo.getExpressfee() != null && orderRo.getExpressfee().compareTo(new BigDecimal(0)) > 0) {
                ammount = ammount.add(orderRo.getExpressfee());
            }
            orderRo.setAmmount(ammount); //实付金额赋值给对象orderRo
            result = service.createOne(orderRo);
            if (result <= 0) {
                this.logger.error("订单创建失败，参数：" + JSON.toJSONString(orderRo));
                return 0L;
            } else {
                //异步保存订单其它信息
                saveOrderOtherInfo(orderRo, result);
            }
        } catch (Exception ex) {
            this.logger.error("createNewOrder 发生异常:" + ex.getMessage());
            ex.printStackTrace();
        }
        return result;
    }

    @Async
    public void saveOrderOtherInfo(AddOrderRo ro, Long orderId) {
        this.logger.debug("订单保存-1.数据写入t_order表成功,orderId:" + orderId);
        //2.保存订单收货信息表
        if (ro.getAddress() != null) {
            OrderAddressRo addressRo = ro.getAddress();
            OrderAddress orderAddress = new OrderAddress();
            orderAddress.setName(addressRo.getName());
            orderAddress.setMobile(addressRo.getMobile());
            orderAddress.setOrderid(orderId);
            orderAddress.setState(addressRo.getState());
            orderAddress.setCity(addressRo.getCity());
            orderAddress.setDistrict(addressRo.getDistrict());
            orderAddress.setAddress(addressRo.getAddress());
            orderAddress.setCreatetime(new Date());
            //获取所在小区的团长Id,将团长Id保存到订单收货地址表中
           Long masterId= areaService.getMasterId(addressRo.getDistrict());
           orderAddress.setMasterid(masterId);
            int result = this.orderAddressMapper.insertSelective(orderAddress);
            if (result <= 0) {

                this.logger.error("createOne 异常，数据写入t_order_address表失败");
            } else {
                this.logger.debug("订单保存-2.数据写入t_order_address表成功,orderId:" + orderId);
            }
        }
        //3.保存订单商品表
        if (ro.getItems() != null && ro.getItems().size() > 0) {
            int totalSize = ro.getItems().size();

            int successSize = 0;
            OrderItem orderItem;
            for (OrderItemRo itemRo : ro.getItems()) {
                orderItem = new OrderItem();
                orderItem.setOrderid(orderId);
                orderItem.setItemid(itemRo.getItemid());
                orderItem.setNum(itemRo.getNum());
                orderItem.setPrice(itemRo.getPrice());
                orderItem.setTotal(itemRo.getTotal());
                orderItem.setPicurl(itemRo.getPicurl());
                orderItem.setTitle(itemRo.getTitle());
                orderItem.setStoredid(itemRo.getStoredid());
                orderItem.setType(itemRo.getType());
                if (this.orderItemMapper.insertSelective(orderItem) > 0) {
                    successSize++;
                }
            }
            if (totalSize == successSize) {
                this.logger.debug("订单保存-2.数据写入t_order_item表成功,orderId:" + orderId);
            } else {
                this.logger.error(String.format("createOne 异常，数据写入t_order_item表,总数：%d,成功数:%d", totalSize, successSize));
            }

        }
    }

    @Async
    public void saveOrderPayingLog(Order order) {
        OrderPaying orderPaying = new OrderPaying();
        orderPaying.setOrderid(order.getId());
        orderPaying.setOrdercode(order.getCode());
        orderPayingService.saveOne(orderPaying);
    }

    @Async
    public void removeOrderPayingLog(Long orderid) {
        orderPayingService.deleteOne(orderid);
    }

    /**
     * 发送短信通知逛呗管理员
     */
    @Async
    public void sendMessage(String apiUrl, FeigeMessageInfo messageInfo, Order order) {
        HTTPUtil httpUtil = new HTTPUtil(false, HTTPUtil.CONTENTTYPE_JSON);
        httpUtil.sendRequestPost(apiUrl, JSONObject.toJSONString(messageInfo));
    }
}
